﻿namespace ClassyBlog.Web
{
    using System;
    using System.Web.Mvc;

    using Infrastructure;

    public class ContentProxyController : AsyncController
    {
        private readonly IHttp http;

        public ContentProxyController(IHttp http)
        {
            if (http == null)
            {
                throw new ArgumentNullException("http");
            }

            this.http = http;
        }

        [HttpGet]
        public void GetAsync(string url)
        {
            AsyncManager.OutstandingOperations.Increment();

            http.GetAsync(
                            new Uri(url),
                            (error, statusCode, type, content) =>
                            {
                                AsyncManager.Parameters["error"] = error;
                                AsyncManager.Parameters["statusCode"] = statusCode;
                                AsyncManager.Parameters["type"] = type;
                                AsyncManager.Parameters["content"] = content;

                                AsyncManager.OutstandingOperations.Decrement();
                            });
        }

        public ActionResult GetCompleted(
            bool error, int statusCode, string type, string content)
        {
            return error ?
                   new HttpStatusCodeResult(statusCode) :
                   Content(content, type) as ActionResult;
        }
    }
}